import {request} from "../../utils/request";
import config from "../../utils/config";
import {$wuxCountDown} from '../../lib/index'

const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        picUrl: config.picUrl,
        custom: wx.getMenuButtonBoundingClientRect(),
        user: {},
        order_id: null,
        order: {},
        c1: '',
        c2: '',
        c3: '',
        type: 1,
        hideShadow: true,
        hideFahuo: true,
        expressList: [],
        express: {},
        address: '',
        orderIndex: null,
        sole: {},
        poster:'',
        hidePoster: true,
    },
    onLoad(options) {
        wx.hideShareMenu()
        var user = wx.getStorageSync('userInfo'),
            order_id = options.id
        this.setData({user, order_id})
        this.getDetail()
        this.getExpress()
        if ('type' in options) {
            this.setData({type: options.type})
        }
    },
    getDetail() {
        request({
            url: "/miniprogram/order/getMyOrderDetail2",
            data: {id: this.data.order_id},
            type: "post"
        }).then(res => {
            if (res.code == 200) {
                this.setData({order: res.data})
                if (res.data.status == 2) {
                    this.c1 = new $wuxCountDown({
                        date: res.data.auto_confirm_time,
                        render(date) {
                            let days = this.leadingZeros(date.days, 0) + ' 天 '
                            let hours = this.leadingZeros(date.hours, 0) + ' 时 '
                            let min = this.leadingZeros(date.min, 2) + ' 分 '
                            let sec = this.leadingZeros(date.sec, 2) + ' 秒 '
                            if (days == '0 天 ') days = '';
                            if (days == '' && hours == '0 时 ') hours = '';
                            if (days == '' && hours == '' && min == '0 分 ') min = '';
                            this.setData({
                                c1: days + hours + min + sec,
                            })
                        },
                    })
                } else if (res.data.status == 0) {
                    this.c2 = new $wuxCountDown({
                        date: res.data.auto_cancel_time,
                        render(date) {
                            let days = this.leadingZeros(date.days, 0) + ' 天 '
                            let hours = this.leadingZeros(date.hours, 0) + ' 时 '
                            let min = this.leadingZeros(date.min, 2) + ' 分 '
                            let sec = this.leadingZeros(date.sec, 2) + ' 秒 '
                            if (days == '0 天 ') days = '';
                            if (days == '' && hours == '0 时 ') hours = '';
                            if (days == '' && hours == '' && min == '0 分 ') min = '';
                            this.setData({
                                c2: days + hours + min + sec,
                            })
                        },
                    })
                }else if(res.data.status == 9){
                    this.c3 = new $wuxCountDown({
                        date: res.data.yanchang_time,
                        render(date) {
                            let days = this.leadingZeros(date.days, 0) + ' 天 '
                            let hours = this.leadingZeros(date.hours, 0) + ' 时 '
                            let min = this.leadingZeros(date.min, 2) + ' 分 '
                            let sec = this.leadingZeros(date.sec, 2) + ' 秒 '
                            if (days == '0 天 ') days = '';
                            if (days == '' && hours == '0 时 ') hours = '';
                            if (days == '' && hours == '' && min == '0 分 ') min = '';
                            this.setData({
                                c3: days + hours + min + sec,
                            })
                        },
                    })
                }
            }
        })
    },
    catPoster(e) {
        var id = e.currentTarget.dataset.id
        wx.showLoading()
        request({
            url: '/miniprogram/order/poster',
            data: {id}
        }).then(res => {
            wx.hideLoading()
            if (res.code != 200) {
                config.toast(res.msg, res.code, () => {})
                return false
            } else if (Object.prototype.isPrototypeOf(res.data) && Object.keys(res.data).length === 0) {
                config.toast('未找到对应授权信息。', res.code, () => {})
                return false
            }else{
                this.setData({poster: res.data, hideShadow: false, hidePoster: false})
            }
        })
        return false
        wx.showLoading()
        request({
            url: '/miniprogram/order/poster',
            data: {order_id: this.data.order_id}
        }).then(res => {
            wx.hideLoading()
            if (res.code != 200) {
                config.toast(res.msg, res.code, () => {
                })
            } else if (Object.prototype.isPrototypeOf(res.data) && Object.keys(res.data).length === 0) {
                config.toast('未找到对应授权信息。', res.code, () => {
                })
            }
            this.setData({sole: res.data, hideShadow: false, hidePoster: false})
        })
    },
    rePayOrder(e) {
        var _this = this,
            order = this.data.order
        if (order.goods.length == 1 && (order.goods[0].type == 2 || order.goods[0].type == 3)) {
            request({
                url: "/miniprogram/order/checkIsSoled",
                data: {user_id: this.data.user.id, good_id: order.goods[0].good_id}
            }).then(res => {
                if (res.code != 200) {
                    config.toast(res.msg, res.code, () => {
                    })
                } else {
                    request({
                        url: "/miniprogram/lklpay/reCreateOrder",
                        data: {
                            openid: this.data.user.openid,
                            id: this.data.order_id,
                            user_id: this.data.user.id,
                            nickname: this.data.user.nickname
                        },
                        type: 'post'
                    }).then(res => {
                        if(res.code !== 200){
                            config.toast(res.msg,201,()=>{})
                            return false
                        }
                        wx.showLoading()
                        wx.requestPayment({
                            timeStamp: res.data.acc_resp_fields.time_stamp,
                            nonceStr: res.data.acc_resp_fields.nonce_str,
                            package: res.data.acc_resp_fields.package,
                            signType: res.data.acc_resp_fields.sign_type,
                            paySign: res.data.acc_resp_fields.pay_sign,
                            success(rel) {
                                setTimeout(() => {
                                    request({
                                        url: "/miniprogram/lklpay/queryOrder",
                                        data: {out_trade_no: res.data.out_trade_no}
                                    }).then(res2 => {
                                        config.toast(res2.msg, res2.code, () => {
                                            if (res2.code == 200) {
                                                _this.setData({
                                                    ['order.status']: 1
                                                })
                                            }
                                        })
                                    })
                                }, 1500)
                            },
                            fail(err) {
                                wx.hideLoading()
                            }
                        })
                    })
                }
            })
        } else {
            request({
                url: "/miniprogram/lklpay/reCreateOrder",
                data: {
                    openid: this.data.user.openid,
                    id: this.data.order_id,
                    user_id: this.data.user.id,
                    nickname: this.data.user.nickname
                },
                type: 'post'
            }).then(res => {
                if(res.code !== 200){
                    config.toast(res.msg,201,()=>{})
                    return false
                }
                wx.showLoading()
                wx.requestPayment({
                    timeStamp: res.data.acc_resp_fields.time_stamp,
                    nonceStr: res.data.acc_resp_fields.nonce_str,
                    package: res.data.acc_resp_fields.package,
                    signType: res.data.acc_resp_fields.sign_type,
                    paySign: res.data.acc_resp_fields.pay_sign,
                    success(rel) {
                        setTimeout(() => {
                            request({
                                url: "/miniprogram/lklpay/queryOrder",
                                data: {out_trade_no: res.data.out_trade_no}
                            }).then(res2 => {
                                config.toast(res2.msg, res2.code, () => {
                                    if (res2.code == 200) {
                                        _this.setData({
                                            ['order.status']: 1
                                        })
                                    }
                                })
                            })
                        }, 1500)
                    },
                    fail(err) {
                        wx.hideLoading()
                    }
                })
            })
        }
    },
    cancelOrder() {
        wx.showModal({
            title:'真的要取消订单吗？',
            success:rel=>{
                if(rel.confirm){
                    request({
                        url: "/miniprogram/order/handleCancelOrder",
                        data: {id: this.data.order_id}
                    }).then(res => {
                        config.toast(res.msg, res.code, () => {
                            if (res.code == 200) {
                                this.setData({
                                    ['order.status']: -1
                                })
                            }
                        })
                    })
                }
            }

        })

    },
    confirmOrder() {
        wx.showModal({
            title: '提示',
            content: '请确认您已收到货物并确认产品无误，确认后无法再进行退货操作。',
            success: (res) => {
                if (res.cancel) return false
                wx.showLoading()
                request({
                    url: "/miniprogram/lklpay/handleConfirmOrder",
                    data: {id: this.data.order_id}
                }).then(res => {
                    wx.hideLoading()
                    config.toast(res.msg, res.code, () => {
                        if (res.code == 200) {
                            this.setData({
                                ['order.status']: 3
                            })
                        }
                    })
                })
            }
        })

    },
    fahuo(e) {
        if(this.data.type == 2){
            //卖家发货，获取order.user_address中的信息
            var {id, index} = e.currentTarget.dataset
            this.setData({
                hideShadow: false,
                hideFahuo: false,
                address: '姓名：' + this.data.order.user_address.name + ' 地址：' + this.data.order.user_address.province + this.data.order.user_address.city + this.data.order.user_address.county + this.data.order.user_address.address + ' 电话：' + this.data.order.user_address.phone,
                orderIndex: index
            })
        }else{
            this.setData({
                hideShadow: false,
                hideFahuo: false,
                address: '姓名：' + this.data.order.saler.shop_name + ' 地址：' + this.data.order.saler.province + this.data.order.saler.city + this.data.order.saler.county + this.data.order.saler.shop_address + ' 电话：' + this.data.order.saler.phone,
                orderIndex: index
            })
        }
    },
    getExpress() {
        request({url: "/miniprogram/system/getExpress"}).then(res => {
            this.setData({expressList: res.data})
        })
    },
    changeExpress(e) {
        console.log(1)
        this.setData({express: this.data.expressList[e.detail.value]})
    },
    changeValue(e) {
        this.setData({
            ['express.num']: e.detail.value
        })
    },
    submitFahuo() {
        if(this.data.type == 2){
            var url = "/miniprogram/order/fahuo"
        }else{
            var url = "/miniprogram/order/refundWaybill"
        }
        wx.showModal({
            title:'确定要发货吗？',
            success:rel=>{
                if(rel.confirm){
                    request({
                        url: url,
                        data: {
                            id: this.data.order_id,
                            waybill_type: this.data.express.id,
                            waybill: this.data.express.num
                        },
                        type:'post'
                    }).then(res => {
                        this.getDetail()
                        this.closeShadow()
                    })
                }
            }
        })

    },
    copy(e) {
        wx.setClipboardData({
            data: e.currentTarget.dataset.txt,
            success(res) {
            }
        })
    },
    scan() {
        wx.scanCode({
            success: (res) => {
                if (res.errMsg == 'scanCode:ok') {
                    this.setData({['express.num']: res.result})
                    config.toast('我们不保证扫码获取单号的准确性，请扫码后仔细核对！！！', 201, () => {
                    })
                }
            }
        })
    },
    closeShadow() {
        this.setData({
            express: {},
            address: '',
            orderIndex: null,
            hideShadow: true,
            hideFahuo: true,
            hidePoster: true
        })
    },
    savePoster() {
        const that = this
        let fileName = new Date().valueOf();
        let filePath = wx.env.USER_DATA_PATH + '/' + fileName + '.jpg'
        wx.downloadFile({
            url: config.picUrl + this.data.poster,
            filePath: filePath,
            success: res => {
                wx.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success(data) {
                        let fileMgr = wx.getFileSystemManager()
                        fileMgr.unlink({
                            filePath: filePath,
                            success() {
                                wx.showToast({
                                    title: '已保存至您的相册',
                                    icon: 'none',
                                    duration: 1500
                                });
                                that.setData({hidePoster: true, hideShadow: true})
                            }
                        })
                    },
                    fail(err) {
                        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                            wx.showModal({
                                title: '提示',
                                content: '需要您授权保存相册',
                                showCancel: false,
                                success: modalSuccess => {
                                    wx.openSetting({
                                        success(settingdata) {
                                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                config.toast("获取权限成功，再次点击图片保存到相册的。", 201, () => {
                                                })
                                            } else {
                                                config.toast("获取权限失败，授权失败图片无法保存到本地相册", 201, () => {
                                                })
                                            }
                                        }
                                    })
                                }
                            })
                        }
                    }
                })
            }
        })
    },
    tuihuo() {
        wx.showActionSheet({
            alertText: "请选择退货类型",
            itemList: ["未收到货退款", "退款退货"],
            success: res => {
                var refund_type = res.tapIndex + 1
                wx.showActionSheet({
                    alertText: "请选择退货原因",
                    itemList: ["我不想要了", "商品描述不符", "少发/漏发", "包装/商品破损", "假冒品牌", "发票问题"],
                    success: res2 => {
                        var arr = ["我不想要了", "商品描述不符", "少发/漏发", "包装/商品破损", "假冒品牌", "发票问题"]
                        var refund_msg = arr[res2.tapIndex]
                        wx.showLoading()
                        request({
                            url: '/miniprogram/order/initiateReturn',
                            type: 'post',
                            data: {refund_msg, refund_type, id: this.data.order.id}
                        }).then(res => {
                            wx.hideLoading()
                            this.getDetail()
                        })
                    }
                })
            }
        })
    },
    agreeRefund() {
        wx.showLoading()
        request({
            url: '/miniprogram/order/agreeRefund',
            type: 'post',
            data: {id: this.data.order.id}
        }).then(res => {
            config.toast(res.msg,201,()=>{})
            wx.hideLoading()
            this.getDetail()
        })
    },
    agreeRefund2(){
        wx.showLoading()
        request({
            url:'/miniprogram/lklpay/onlyRefund',
            type:'post',
            data:{id:this.data.order.id}
        }).then(res=>{
            config.toast(res.msg,201,()=>{})
            wx.hideLoading()
            this.getDetail()
        })
    },
    refuseRefund(){
        wx.showLoading()
        request({
            url: '/miniprogram/order/refuseRefund',
            type: 'post',
            data: {id: this.data.order.id}
        }).then(res => {
            config.toast(res.msg,res.code,()=>{})
            wx.hideLoading()
            this.getDetail()
        })
    },
    holdRefund() {
        wx.showModal({
            title:'提示',
            content:'真的要确认收到退货吗？确认收货后将会把订单资金退还买方。',
            success:res=>{
                if(res.cancel) return false
                wx.showLoading()
                request({
                    url:'/miniprogram/lklpay/holdRefund',
                    data:{id:this.data.order.id}
                }).then(res=>{
                    config.toast(res.msg,res.code,()=>{})
                    wx.hideLoading()
                    this.getDetail()
                })
            }
        })
    },
    yanchang(){
        wx.showLoading()
        request({
            url:"/miniprogram/order/yanchangshouhuo",
            data:{id:this.data.order.id}
        }).then(res=>{
            wx.hideLoading()
            config.toast(res.msg,res.code,()=>{})
            this.getDetail()
        })
    }

})